package com.hdax.dm.mq;

import com.hdax.dm.feign.schedulerFeign;
import com.hdax.dm.service.queryorderlistService;
import com.hdax.dm.service.submitorderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RabbitListener(queues = {"linkuser_rollback","seat_rollback","order_rollback"})
@Component
public class OrderMqListener {

    @Autowired
    private queryorderlistService queryorderlistService;

    @Autowired
    private submitorderService submitorderService;

    @Autowired
    private schedulerFeign schedulerFeign;

    @Autowired
    private RedisTemplate redisTemplate;


    //订单联系人新增失败的数据回滚
    @RabbitHandler
    public void rollbackLinkUser(Channel channel, Message message, String orderNo) throws IOException {
        redisTemplate.delete("lock");
        //获取队列名称
        String queue = message.getMessageProperties().getConsumerQueue();
        //获取到唯一tag
        long tag = message.getMessageProperties().getDeliveryTag();
        if(queue.equals("linkuser_rollback")){
            System.out.println("linkuser_rollback");
            Integer flag = submitorderService.deleteorderLinkUser(orderNo);
            if (flag>0) {
                channel.basicAck(tag,false);
            }else {
//                //basicNack(tag, 是否批量, 是否重回队列)
                channel.basicNack(tag,false,false);
            }
        }else if(queue.equals("order_rollback")){
            System.out.println("order_rollback");
            Integer flag = queryorderlistService.Timeoutupdate(orderNo);
            if (flag>0) {
                channel.basicAck(tag,false);
            }else {
                channel.basicNack(tag,false,false);
            }
        }else if(queue.equals("seat_rollback")){
            System.out.println("seat_rollback");
            Integer flag = schedulerFeign.updateseat(orderNo);
            if (flag>0) {
                channel.basicAck(tag,false);
            }else {
                channel.basicNack(tag,false,false);
            }
        }
    }
}
